/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 */

package com.nail.zhaogr.front.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.web.scope.Flash;
import cn.org.rapid_framework.web.util.HttpUtils;

import com.nail.zhaogr.model.Category;
import com.nail.zhaogr.model.City;
import com.nail.zhaogr.model.Members;
import com.nail.zhaogr.model.MyCommend;
import com.nail.zhaogr.model.MyContact;
import com.nail.zhaogr.model.MyFavorite;
import com.nail.zhaogr.model.PsnServiceArea;
import com.nail.zhaogr.model.PublishInfo;
import com.nail.zhaogr.service.CategoryManager;
import com.nail.zhaogr.service.CityManager;
import com.nail.zhaogr.service.MembersManager;
import com.nail.zhaogr.service.MyContactManager;
import com.nail.zhaogr.service.PublishInfoManager;
import com.nail.zhaogr.vo.query.MyCommendQuery;
import com.nail.zhaogr.vo.query.MyFavoriteQuery;
import com.nail.zhaogr.vo.query.PublishInfoQuery;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */


public class PublishInfoAction extends BaseAction{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = "updateTime desc"; 
	 
	//forward paths
	protected static final String QUERY_JSP = "/pages/PublishInfo/query.jsp";
	protected static final String LIST_JSP= "/main.jsp";
	protected static final String CREATE_JSP = "/front/PublishInfo/create.jsp";
	protected static final String EDIT_JSP = "/front/PublishInfo/edit.jsp";
	protected static final String SHOW_JSP = "/front/PublishInfo/show.jsp";
	
	protected static final String Member_JSP = "/front/Members/memberIndex.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/front/MemberCenter/index.do";
	
	protected static final String Create_SUCCESS = "/commons/success.jsp";
	
	protected static final String Member_SUCCESS = "/front/Members/operSuccess.jsp";
	
	protected static final String Register_index = "!/Register/indexMembers.do";
	
	private PublishInfoManager publishInfoManager;
	
	private CityManager cityManager;
	private CategoryManager categoryManager;
	private MembersManager membersManager;
	private MyContactManager myContactManager;
	
	private PublishInfo publishInfo;
	java.lang.Long id = null;
	private String[] items;
	
	private List<City> cityList;
	private List<Category> categoryList;
	
	private List<PublishInfo> publishInfoList;
	
	private String[] serviceAreas;
	
	private String[] categoryIds;
	private MyCommend myCommend;
	private MyFavorite myFavorite;
	public void prepare() throws Exception {
		this.getPageUrl();
		if (isNullOrEmptyString(id)) {
			publishInfo = new PublishInfo();
		} else {
			publishInfo = (PublishInfo)publishInfoManager.getById(id);
		}
	}
	
	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性 */
	public void setPublishInfoManager(PublishInfoManager manager) {
		this.publishInfoManager = manager;
	}	
	
	public Object getModel() {
		return publishInfo;
	}
	
	public void setPublishInfoId(java.lang.Long val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 进入查询页面 */
	public String query() {
		return QUERY_JSP;
	}
	
	/** 执行搜索 */
	public String list() {
		
		PublishInfoQuery query = newQuery(PublishInfoQuery.class,DEFAULT_SORT_COLUMNS);
		
		//this.setTitle(publishInfo.getCategory().getCategoryName()+"-"+publishInfo.getCityThree()+"_"+publishInfo.getCityTwo()+"找工人"+"_");
		
		query.setStatus(1);
		query.setType(1);
		query.setParentCityId(getCurrentCity().getCityId());
		//query.setPageSize(1);
		Page page = publishInfoManager.findPage(query);
		limitLength(page);
		savePage(page,query);
		return LIST_JSP;
	}
	
	public String showPhone(){
		try {
			Members memberInfo = this.getMemberInfo();
			//登录才能查看电话号码
			if(memberInfo!=null){
				//判断会员积分
				if(memberInfo.getPoints()>0){
					memberInfo.setPoints(memberInfo.getPoints()-2);
					membersManager.update(memberInfo);
					MyContact entity = new MyContact();
					entity.setMemberId(memberInfo.getMemberId());
					entity.setPublishInfoId(publishInfo.getPublishInfoId());
					entity.setTradeTime(new Date(System.currentTimeMillis()));
					entity.setEndTime(new Date(System.currentTimeMillis()));
					entity.setStatus(0);
					myContactManager.save(entity);
					
					this.getResponse().getWriter().write(publishInfo.getPhone());
				}else{//积分不够
					this.getResponse().getWriter().write("0");
				}
			}else{
				this.getResponse().getWriter().write("-1");
			}
		} catch (IOException e) {
		}
		return null;
	}
	
	/** 查看对象*/
	public String show() {
		this.setTitle(publishInfo.getCategory().getCategoryName()+"-"+publishInfo.getCityThree()+"_"+publishInfo.getCityTwo()+"找工人"+"_");
		this.setMetaDesc(publishInfo.getProfile());
		if(publishInfo.getCommentss().size()>10){
			publishInfo.setCommentss(publishInfo.getCommentss().subList(0, 10));
		}
		MyContact psnTrade = new MyContact();
		if(this.getMemberInfo()!=null){
			psnTrade.setMemberId(this.getMemberInfo().getMemberId());
			psnTrade.setPublishInfoId(id);
			if(myContactManager.isMemberTrade(psnTrade)){
				publishInfo.setHasTrade(1);
			}
		}
		return SHOW_JSP;
	}
	
	/** 进入新增页面*/
	public String create() {
		//成都市
		cityList = cityManager.findChildCity(getCurrentCity().getCityId());
		categoryList = categoryManager.findAll();
		return CREATE_JSP;
	}
	
	/** 保存新增对象 */
	public String save() {
		if(!this.filterPublishInfoKeywords(publishInfo)){
			Flash.current().error("您所提交的信息中有不合法，不文明的词语，请修改后再发布");
			Long cityId = getCurrentCity().getCityId();
			cityList = cityManager.findChildCity(cityId);
			categoryList = categoryManager.findAll();
			return CREATE_JSP;
		}
		Members memberInfo = this.getMemberInfo();
		if(memberInfo!=null)
		{
			//publishInfo.setServiceArea(Arrays.toString(serviceAreas));
			publishInfo.setMemberId(memberInfo.getMemberId());
			publishInfo.setStatus(0);
			publishInfo.setCreateDate(new Timestamp(System.currentTimeMillis()));
			publishInfo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			publishInfo.setType(1);
			List psnServiceAreas = new ArrayList();
			//List psninfoCategorys = new ArrayList();
			
			for (int i = 0; i < serviceAreas.length; i++) {
				PsnServiceArea psnServiceArea = new PsnServiceArea();
				psnServiceArea.setPublishInfoId(publishInfo.getPublishInfoId());
				psnServiceArea.setCityId(Long.valueOf(serviceAreas[i]));
				psnServiceAreas.add(psnServiceArea);
				//psnServiceAreaManager.save(psnServiceArea);
			}
			
			/*for (int i = 0; i < categoryIds.length; i++) {
				PsninfoCategory publishInfoCategory = new PsninfoCategory();
				publishInfoCategory.setPublishInfoId(publishInfo.getPublishInfoId());
				publishInfoCategory.setCategoryId(Long.valueOf(categoryIds[i]));
				psninfoCategorys.add(publishInfoCategory);
				//psninfoCategoryManager.save(publishInfoCategory);
			}*/
			publishInfoManager.saveAllInfo(publishInfo,psnServiceAreas);
			//publishInfoManager.save(publishInfo);
			Flash.current().success("您的信息发布成功，需要审核通过才能正常显示");
		}else{
			Flash.current().error("请先注册再发布信息");
			return  Register_index;
		}
		return Create_SUCCESS;
	}
	
	/**进入更新页面*/
	public String edit() {
		Long cityId = getCurrentCity().getCityId();
		cityList = cityManager.findChildCity(cityId);
		categoryList = categoryManager.findAll();
		return EDIT_JSP;
	}
	
	public String memberCenter(){
		return Member_JSP;
	}
	
	/**保存更新对象*/
	public String update() {
		if(!this.filterPublishInfoKeywords(publishInfo)){
			Flash.current().error("您所提交的信息中有不合法，不文明的词语，请修改后再发布");
			Long cityId = getCurrentCity().getCityId();
			cityList = cityManager.findChildCity(cityId);
			categoryList = categoryManager.findAll();
			return EDIT_JSP;
		}
		PublishInfo orgEntity = publishInfoManager.getById(id);
		orgEntity.setCityId(publishInfo.getCityId());
		orgEntity.setCategoryId(publishInfo.getCategoryId());
		orgEntity.setAddress(publishInfo.getAddress());
		orgEntity.setPhone(publishInfo.getPhone());
		orgEntity.setName(publishInfo.getName());
		orgEntity.setProfile(publishInfo.getProfile());
		orgEntity.setStatus(0);
		publishInfoManager.update(orgEntity);
		Flash.current().success("信息更新成功");
		return Create_SUCCESS;
	}
	
	/**删除对象*/
	public String delete() {
		for(int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			java.lang.Long id = new java.lang.Long((String)params.get("publishInfoId"));
			publishInfoManager.removeById(id);
		}
		return LIST_ACTION;
	}
	
	public String close() {
		publishInfo.setStatus(3);
		publishInfoManager.save(publishInfo);
		Flash.current().success("信息关闭成功");
		return Member_SUCCESS;
	}
	
	public String open() {
		publishInfo.setStatus(1);
		publishInfoManager.save(publishInfo);
		Flash.current().success("信息重新发布成功");
		return Member_SUCCESS;
	}
	
	//我要推荐
	public String commend(){
		try {
			MyCommendQuery query = newQuery(MyCommendQuery.class,"");
			String returnStr = publishInfoManager.saveCommend(query);
			this.getResponse().getWriter().write(returnStr);
		} catch (IOException e) {
		}
		return null;
	}
	
	//我要收藏
	public String favorite(){
		try {
			MyFavoriteQuery query = newQuery(MyFavoriteQuery.class,"");
			String returnStr = publishInfoManager.saveFavorite(query);
			this.getResponse().getWriter().write(returnStr);
		} catch (IOException e) {
		}
		return null;
	}
	

	public List<City> getCityList() {
		return cityList;
	}

	public void setCityList(List<City> cityList) {
		this.cityList = cityList;
	}

	public List<Category> getCategoryList() {
		return categoryList;
	}

	public void setCategoryList(List<Category> categoryList) {
		this.categoryList = categoryList;
	}


	public void setCityManager(CityManager cityManager) {
		this.cityManager = cityManager;
	}

	public void setCategoryManager(CategoryManager categoryManager) {
		this.categoryManager = categoryManager;
	}

	public List<PublishInfo> getPublishInfoList() {
		return publishInfoList;
	}

	public void setPublishInfoList(List<PublishInfo> publishInfoList) {
		this.publishInfoList = publishInfoList;
	}

	/**
	 * @return the serviceAreas
	 */
	public String[] getServiceAreas() {
		return serviceAreas;
	}

	/**
	 * @param serviceAreas the serviceAreas to set
	 */
	public void setServiceAreas(String[] serviceAreas) {
		this.serviceAreas = serviceAreas;
	}

	/**
	 * @return the categoryIds
	 */
	public String[] getCategoryIds() {
		return categoryIds;
	}

	/**
	 * @param categoryIds the categoryIds to set
	 */
	public void setCategoryIds(String[] categoryIds) {
		this.categoryIds = categoryIds;
	}

	public void setMembersManager(MembersManager membersManager) {
		this.membersManager = membersManager;
	}

	/**
	 * @param myContactManager the myContactManager to set
	 */
	public void setMyContactManager(MyContactManager myContactManager) {
		this.myContactManager = myContactManager;
	}

	/**
	 * @return the myCommend
	 */
	public MyCommend getMyCommend() {
		return myCommend;
	}

	/**
	 * @param myCommend the myCommend to set
	 */
	public void setMyCommend(MyCommend myCommend) {
		this.myCommend = myCommend;
	}

	/**
	 * @return the myFavorite
	 */
	public MyFavorite getMyFavorite() {
		return myFavorite;
	}

	/**
	 * @param myFavorite the myFavorite to set
	 */
	public void setMyFavorite(MyFavorite myFavorite) {
		this.myFavorite = myFavorite;
	}


}
